﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using WebCommit.Common.Entitys;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using WebCommit.Common.Enums;
using WebCommit.Common;
using NHibernate;
using WebCommit.Common.Helpers;
using NHibernate.Criterion;

namespace WebCommit.Crawler
{
	public partial class CrawlerFrom : Form
	{
		public CrawlerFrom()
		{
			InitializeComponent();
		}

		
		CrawlerManager manager;
		BindingSource bindingSource = new BindingSource();
		List<WebResourceEntity> dataSource = new List<WebResourceEntity>();
		System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
		
		DateTime beginTime;
		object lockObj = new object();
		private void btnStart_Click(object sender, EventArgs e)
		{
			if (manager == null)
			{
				beginTime = DateTime.Now;
				CreateManager();
			}
			btnStop.Enabled = true;
			btnStart.Enabled = false;
			manager.Start();
			//BindGrid();
		}

		private void CreateManager()
		{
			List<WebResourceEntity> list = new List<WebResourceEntity>();
			list.Add(new WebResourceEntity() { Url = this.txtStartUpUrl.Text });
			manager = new CrawlerManager(list);
			manager.Started += new CrawlerManager.OnStarted(manager_Started);
			manager.Stoped += new CrawlerManager.OnStoped(manager_Stoped);
			//manager.ProgressChanged += new CrawlerManager.OnProgressChanged(worker_ProgressChanged);
			
		}

		void manager_Stoped(object sender, WorkerEventArgs e)
		{
			timer.Stop();
		}

		void manager_Started(object sender, WorkerEventArgs e)
		{
			this.timer.Start();
		}

		void worker_ProgressChanged(object sender, WorkerEventArgs e)
		{
			//BindSource();;
			if (this.InvokeRequired)
			{
				this.Invoke(new Action(RefleshStatus));
			}
			else
			{
				RefleshStatus();
			}
		}

		private void RefleshStatus()
		{

			try
			{
				string str = "Web:{0}({1}/秒) UrlOK:{2}({3}/秒) WebOK:{4}({5}/秒) 耗时:{6}秒 ";
				TimeSpan ts = DateTime.Now - beginTime;
				double sec = ts.TotalSeconds;
				double web = manager.WebList.Count;
				double urlOK = manager.WebList.Count(w => w.UrlCrawlStatus == CrawlStatus.OK);
				double webOK = manager.WebList.Count(w => w.WebCrawlStatus == CrawlStatus.OK);
				if (sec == 0)
					sec = 1;

				statusAll.Text = string.Format(str,
					web,
					(web / sec).ToString("#.##"),
					urlOK,
					(urlOK / sec).ToString("#.##"),
					webOK,
					(webOK / sec).ToString("#.##"),
					sec);

			}
			catch
			{ }
			if (chkBoxAutoFlesh.Checked)
				BindGrid();
		}


		private void BindGrid()
		{
			if (this.InvokeRequired)
			{
				this.Invoke(new Action(RefleshGrid));
			}
			else
			{
				RefleshGrid();
			}
		}

		private void RefleshGrid()
		{

			BindingSource source = new BindingSource();
			source.DataSource = manager.WebList.FindAll(w => w.UrlCrawlStatus != CrawlStatus.Pending || w.WebCrawlStatus != CrawlStatus.Pending);
			if (this.chkBoxAutoScroll.Checked)
				source.MoveLast();
			this.gridWaiting.DataSource = source;
		}

		private void btnStop_Click(object sender, EventArgs e)
		{
			btnStop.Enabled = false;
			btnStart.Enabled = true;
			manager.Stop();
		}

		//private string GetChartset(Stream stream)
		//{
		//    byte[] buffer = new byte[1024];
		//    stream.Read(buffer, 0, 1024);

		//}


		private void CrawlerFrom_Load(object sender, EventArgs e)
		{
			timer.Interval = 1000;
			timer.Tick += new EventHandler(timer_Tick);
		//	CreateManager();
		}

		void timer_Tick(object sender, EventArgs e)
		{
			RefleshStatus();
		}

		private void btnReflesh_Click(object sender, EventArgs e)
		{
			BindGrid();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			//Uri u = new Uri("http://a.a.a/b/c/d?e=f");
			//WebResourceEntity w = new WebResourceEntity() { CharacterSet = "UTF-8", Domain = "www.sina.com.cn", ErrorMsg = "", RootDomain = "sina.com.cn", Source = WebSource.Crawler, Title = "新浪", Url = "http://www.sina.com.cn/", UrlCrawlStatus = CrawlStatus.OK, WebCrawlStatus = CrawlStatus.OK };
			ISession session = NHibernateHelper.GetSession("webcommit");
			ITransaction tran = session.BeginTransaction();
			UserAttachEntity u = new UserAttachEntity();
			u.LastLoginGeo = new Common.Models.GeoPosition() { Latitude = "lat", Longitude = "lng", Country = "cy", Region = "reg", City = "ct", Local = "loc" };
			session.Save(u);
			tran.Commit();
			MessageBox.Show(session.Get<UserAttachEntity>("2125b847-29ed-4584-a9c4-7fb38130eac8").LastLoginGeo.ToString());
			
		}

		private void button2_Click(object sender, EventArgs e)
		{
			ISession session = NHibernateHelper.GetSession("webcommit");
			
			//ISession session = NHibernateHelper.GetSession("webcommit");
			//IQuery q = session.CreateQuery("from WebResource");
			//IList<WebResourceEntity> list = q.List<WebResourceEntity>();


		}


	}
}
